<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="/css/bootstrap-4.6.2-dist/css/bootstrap.min.css">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="/css/bootstrap-4.6.2-dist/js/bootstrap.min.js"></script>
    <script src="/js/date.js"></script>


</head>
<body>
<div class="container">
    <div class="text-center">
        <h1>用户信息</h1>
        <p>账号：<span id="loginAccount"></span></p>
        <p>用户名称：<span id="loginName"></span></p>

    </div>

    <!-- Button trigger modal -->
    <div style="margin-top: 40px">
        <span>
            <button type="button" onclick="show(1)" class="btn btn-info">
            添加产品
            </button>
        </span>
        <span style="float: right">
            <button id="logout" type="button" class="btn btn-info">
         退出登录
            </button>
        </span>
    </div>


    <!-- Modal -->
    <div class="modal fade " id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="false">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-body">
                    <div class="form-group">
                        <input type="hidden" class="form-control" id="productId">
                        <input type="text" class="form-control" id="productName" placeholder="产品名称">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                    <button type="button" id="addSend" class="btn btn-primary" data-dismiss="modal">确定添加</button>
                    <button type="button" id="update" class="btn btn-primary" data-dismiss="modal">确定修改</button>
                </div>
            </div>
        </div>
    </div>


    <table class="table table-hover">
        <thead>
        <tr>
            <th scope="col">序号</th>
            <th scope="col">产品名称</th>
            <th scope="col">创建人</th>
            <th scope="col">创建时间</th>
            <th scope="col">修改人</th>
            <th scope="col">修改时间</th>
            <th scope="col">操作</th>
        </tr>
        </thead>
        <tbody id="body">
        </tbody>
    </table>

    <div style="float: right">
        <nav aria-label="Page navigation example">
            <ul class="pagination" id="page">
            </ul>
        </nav>
    </div>
    <div style="float: right;margin-right: 30px;padding-top: 8px">
        <span>总记录数 <span id="count" style="color: rgba(205,92,6,0.87)"></span> 条</span>
    </div>
</div>
<script>

    $(function () {
        load();
    })

    $("#logout").click(function () {
        $.ajax({
            url: "/logout",
            type: "GET",
            headers: {
                "Authorization": localStorage.getItem("token")
            },
            success: function (responseData) {
                if (responseData.code == 200) {
                    alert(responseData.message)
                    localStorage.clear()
                    window.location.href = "/login";
                } else {
                    alert(responseData.message)
                }
            },
            error: function () {
                console.log("出错啦...");
            }
        });
    })


    // 添加产品
    $("#addSend").click(function () {

        let productName = $("#productName").val()

        let data = JSON.stringify({"productName": productName});

        $.ajax({
            url: "/product/add",
            type: "POST",
            data: data,
            contentType: "application/json",
            dataType: "json",
            headers: {
                "Authorization": localStorage.getItem("token")
            },
            success: function (responseData) {
                console.log(responseData);

                if (responseData.code == 200) {
                    alert("添加成功");
                    console.log("添加成功");
                    load();
                } else {
                    alert(responseData.message);
                }
            },
            error: function (xhr, status, error) {
                alert("请求失败：" + error);
                console.log("请求失败：" + error);
            }
        });

    });

    // 修改产品
    $("#update").click(function () {
        let productName = $("#productName").val()
        let productId = $("#productId").val()

        let data = JSON.stringify({"productName": productName, "id": productId});

        $.ajax({
            url: "/product/update",
            type: "POST",
            data: data,
            contentType: "application/json",
            headers: {
                "Authorization": localStorage.getItem("token")
            },
            dataType: "json",
            success: function (responseData) {
                console.log(responseData);

                if (responseData.code == 200) {
                    console.log("修改成功");
                    alert("修改成功");
                    let currentPageElement = $("#page").find(".page-item.active");
                    let currentPage = parseInt(currentPageElement.find(".page-link").text());
                    pageList(currentPage, 5);
                } else {
                    alert(responseData.message);
                    console.log("修改失败");
                }
            },
            error: function (xhr, status, error) {
                alert("请求失败：" + error);
                console.log("请求失败：" + error);
            }
        });

    });

    $("#add-but").click(function () {
        $('#update').hide();
        $('#addSend').show();
    });

    function load() {
        $('#loginName').html(localStorage.getItem("loginName"))
        $('#loginAccount').html(localStorage.getItem("loginAccount"))
        pageList(1, 5);
    }

    function pageList(current, pageSize) {
        $.ajax({
            url: "/product/listPage/" + current + "/" + pageSize,
            type: "GET",
            headers: {
                "Authorization": localStorage.getItem("token")
            },
            success: function (data) {
                if (data.code == 200) {
                    let pageObj = data.data;
                    let obj = pageObj.data;
                    let str = '';
                    $("#body").empty();

                    let currentPage = pageObj.currentPage;
                    let pageSize = pageObj.pageSize;

                    let idNum = (currentPage - 1) * pageSize;

                    for (let i = 0; i < obj.length; i++) {
                        let o = obj[i];
                        let updateName = '';
                        if (o.updateName !== null) {
                            updateName = o.updateName;
                        }
                        let updateDate = '';

                        if (o.updateDate !== null) {
                            updateDate = UTCformat(o.updateDate);
                        }

                        str += `<tr>
                             <td>` + (idNum + i + 1) + `</td>
                            <td id="` + o.id + `">` + o.productName + `</td>
                            <td>` + o.createName + `</td>
                            <td>` + UTCformat(o.createDate) + `</td>
                            <td>` + updateName + `</td>
                            <td>` + updateDate + `</td>
                            <td>
                             <a class="btn btn-primary btn-sm" onclick="show(2,` + o.id + `)">修改</a>
                            <a class="btn btn-danger btn-sm" onclick="del(` + o.id + `)">删除</a></td>
                            </tr>`;
                    }


                    let totalPage = pageObj.totalPage;
                    let totalCount = pageObj.totalCount;
                    $("#count").html(totalCount);
                    $("#page").empty();


                    let pageStr = '';
                    if (totalCount > 0) {
                        if (currentPage !== 1) {
                            pageStr += '   <li class="page-item">\n' +
                                '                <a class="page-link" href="#" onclick="pageList(' + (currentPage - 1) + ', ' + pageSize + ')" aria-label="Previous">\n' +
                                '                    <span aria-hidden="true">&laquo;</span>\n' +
                                '                </a>\n' +
                                '            </li>';
                        }
                    }

                    for (let i = 1; i <= pageObj.totalPage; i++) {
                        if (i === currentPage) {
                            pageStr += '<li class="page-item  active" aria-current="page"> <span class="page-link">' + i + '</span></li>';
                        } else {
                            pageStr += '<li class="page-item"><a class="page-link" onclick="pageList(' + i + ', ' + pageSize + ')" href="#">' + i + '</a></li>';
                        }
                    }
                    if (totalCount > 0) {
                        if (currentPage !== totalPage) {
                            pageStr += '   <li class="page-item">\n' +
                                '                <a class="page-link" href="#" onclick="pageList(' + (currentPage + 1) + ', ' + pageSize + ')" aria-label="Previous">\n' +
                                '                    <span aria-hidden="true">&raquo;</span>\n' +
                                '                </a>\n' +
                                '            </li>';
                        }
                    }
                    $("#page").append(pageStr);
                    $("#body").html(str);
                } else if (data.code == 208) {
                    alert(data.message);
                    window.location.href = "/login";

                } else {
                    alert(data.message);
                }
            },
            error: function () {
                console.log("出错啦...");
            }
        });
    }

    function del(id) {
        $.ajax({
            url: "/product/remove/" + id,
            type: "GET",
            headers: {
                "Authorization": localStorage.getItem("token")
            },
            success: function (data) {
                if (data.code == 200) {
                    alert("删除成功")
                    let currentPageElement = $("#page").find(".page-item.active");
                    let currentPage = parseInt(currentPageElement.find(".page-link").text());
                    pageList(currentPage, 5);
                } else {
                    alert(data.message);
                }
            },
            error: function () {
                console.log("出错啦...");
            }
        });
    }

    function show(type, id) {
        if (type == 1) {
            // 是添加
            $('#productName').val('');
            $('#productId').val('');
            $('#addSend').show();
            $('#update').hide();

        } else {
            // 是修改
            let val = $('#' + id).text();
            $('#productName').val(val);
            $('#productId').val(id);
            $('#addSend').hide();
            $('#update').show();
        }

        // 显示弹窗
        $('#exampleModal').modal('show');
    }
</script>
</body>
</html>